package com.idas;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.idas.APIContext;
import com.idas.comp.UserAccess;
import com.idas.db.ConnectionHandler;
import com.sun.net.httpserver.BasicAuthenticator;

import org.apache.log4j.Logger;

public class IDASAuthentication extends BasicAuthenticator {
	private static Logger logger = Logger.getLogger(IDASAuthentication.class);

	public IDASAuthentication(String relam) {
		super(relam);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean checkCredentials(String username, String password) {
		APIContext apiContext = APIContext.getCurrentContext();
		Connection conn = null;
		try {
			conn = ConnectionHandler.getNoTransactionConnection();
			logger.debug("Connection loaded, to check Credentials ");
			
			UserAccess uac = UserAccess.autenticateUser(conn, username,
					password);

			if (uac != null) {
				logger.debug("User Found");
				apiContext.setkey(APIContext.AUTH_USER_KEY, uac);
				return true;
			} else {
				logger.error("Authentication falied");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					ConnectionHandler.endConnection(conn, false);
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}

}